package com.example.demo.config.config;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.config.base.DataModel;
import org.springframework.core.MethodParameter;
import org.springframework.data.domain.Page;
import org.springframework.data.mapping.PropertyReferenceException;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * 统一返回格式;
 */
@ControllerAdvice
public class ResponseJsonHander implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        JSONObject json = new JSONObject();
        if(o instanceof WebException){      //web应用程序运行过程中规定好的错误
            json.put("code", ((WebException) o).code.ordinal() + 100000);
            json.put("message", ((WebException) o).msg);
        }else if(o instanceof Exception){   //web应用运行过程出现未定义的意外错误
            json.put("code", -1);
            json.put("message", ((Exception) o).getMessage());
        }else if(o instanceof JSONObject || o instanceof DataModel || o instanceof Page){    //控制器正常返回的值，为json对象或模型
            json.put("code", 0);
            json.put("data", o);
        }else if(o instanceof List){   //规定data必须是一个可转换成jsonobject的对象，而不是数组
            json.put("code", -2);
            json.put("message", "控制器不允许返回数组，请转换为json对象。");
        }else {                             //包含状态码的其他错误
            json.put("code", -3);
            json.put("message", o);
        }

        return json;
    }
}
